package com.software.frontend.loginAndRegist;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.gjylibrary.GjySerialnumberLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.software.frontend.MainActivity;
import com.software.frontend.R;
import com.software.frontend.loginAndRegist.entity.UserExtends;
import com.software.frontend.loginAndRegist.utils.Result;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoginAndRegisiterByPhoneVarifiyCodeActivity extends AppCompatActivity {

    Button varifyAndLogin;
    ImageView btnBack;
    TextView textVarifyShowPhone, countDownWhite, countDownBlue, hintRegister;
    GjySerialnumberLayout gjySerialnumberLayout;
    private static final String reSendAuthCodeLocation = "login/loginOrRegisterReSendAuthCode";
    private static final String varifyAuthCodeLocation = "login/loginOrRegisterVarifyAuthCode";
    private OkHttpClient okHttpClient = new OkHttpClient();
    private Gson gson = new Gson();
    private String varifyCode;
    private String phoneNumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_and_regisiter_by_phone_varifiy_code);

        initViews();

        staticDataInit();

        initListeners();


    }

    private void staticDataInit() {
        phoneNumber = getIntent().getStringExtra("phoneNumber");
        textVarifyShowPhone.setText(phoneNumber);
        String msg = getIntent().getStringExtra("msg");
        if (!msg.equals("login")) {
            varifyAndLogin.setText("登陆");
        }else {
            varifyAndLogin.setText("注册并登录");
            hintRegister.setVisibility(View.VISIBLE);
        }
    }

    private void initViews() {
        btnBack = (ImageView) findViewById(R.id.button_back);
        varifyAndLogin = (Button) findViewById(R.id.varify_and_login);
        textVarifyShowPhone = (TextView) findViewById(R.id.text_varify_show_phone);
        countDownWhite = (TextView) findViewById(R.id.count_down_white);
        countDownBlue = (TextView) findViewById(R.id.count_down_blue);
        //绑定计时器
        bindingTimmer();
        gjySerialnumberLayout = (GjySerialnumberLayout) findViewById(R.id.gjySerialnumberLayout);
        hintRegister = (TextView) findViewById(R.id.text_hint_register);
    }

    private void initListeners() {

        //返回按钮
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //重新发送
        countDownBlue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (countDownBlue.getText().toString().equals("重新发送")){
                    countDownWhite.setText("重新发送");
                    countDownBlue.setText("60S");
                    //发送后台请求，生成新验证码
                    reSendVarification();
                    //绑定新定时器
                    bindingTimmer();
                }
            }

            /**
             * 重新发送验证码函数
             */
            private void reSendVarification() {
                FormBody formBody = new FormBody.Builder()
                        .add("phoneNumber", phoneNumber)
                        .build();
                Request request = new Request.Builder().url(getResources().getString(R.string.localhost) + reSendAuthCodeLocation).post(formBody).build();
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        Log.i("onFailure" , "访问失败");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String s = response.body().string();
                        Result result = gson.fromJson(s, Result.class);
                        if (result != null && result.getCode() == 200){
                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(LoginAndRegisiterByPhoneVarifiyCodeActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                });
            }
        });

        //输入完毕验证码
        gjySerialnumberLayout.setOnInputListener(new GjySerialnumberLayout.OnInputListener() {
            @Override
            public void onSucess(String code) {
                varifyCode = code;
            }
        });

        //点击登陆
        varifyAndLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (varifyCode != null && varifyCode.length() == 6) {
                    /**
                     *验证码验证函数
                     * 判断并选择跳转
                     * 需要加状态
                     */
                    FormBody formBody = new FormBody.Builder()
                            .add("phoneNumber", phoneNumber)
                            .add("authCode", varifyCode)
                            .build();
                    Request request = new Request.Builder().url(getResources().getString(R.string.localhost) + varifyAuthCodeLocation).post(formBody).build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                            Log.i("onFailure" , "访问失败");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String s = response.body().string();
                            System.out.println(gson);
                            Result result = gson.fromJson(s, new TypeToken<Result<UserExtends>>(){}.getType());
                            if (result != null && result.getCode() == 200){
                                Intent intent = new Intent(LoginAndRegisiterByPhoneVarifiyCodeActivity.this, MainActivity.class);
                                UserExtends userExtends = (UserExtends) (result.getData().get(0));
                                intent.putExtra("usersExtends", userExtends);
                                startActivity(intent);
                                finish();
                            }else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(LoginAndRegisiterByPhoneVarifiyCodeActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    });
                }else {
                    Toast.makeText(LoginAndRegisiterByPhoneVarifiyCodeActivity.this, "请先输入验证码", Toast.LENGTH_SHORT).show();
                }


            }
        });


    }

    private void bindingTimmer() {
        new CountDownTimer(59 * 1000, 1000){
            @Override
            public void onTick(long millisUntilFinished) {
                countDownBlue.setText((Integer.parseInt(countDownBlue.getText().toString().split("S")[0]) - 1) + "");
            }

            @Override
            public void onFinish() {
                countDownWhite.setText("");
                countDownBlue.setText("重新发送");
            }
        }.start();
    }
}